package ace.module.captcha.core.impl.manager.handler.impl;

import ace.cmp.i18n.api.MessageSourceAssertService;
import ace.module.captcha.core.impl.dao.entity.CaptchaComponentConfig;
import ace.module.captcha.core.impl.manager.handler.CaptchaImageHandler;
import ace.module.captcha.core.impl.manager.handler.CaptchaImageHandlerManager;
import ace.module.captcha.core.impl.manager.handler.model.dto.CaptchaImageBase64DataResultDto;
import ace.module.captcha.core.impl.manager.handler.model.dto.CaptchaImageStreamResultDto;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/3/27 11:41 验证码图片组件管理器
 */
@AllArgsConstructor
@Component
public class CaptchaImageHandlerManagerImpl implements CaptchaImageHandlerManager {
  private final List<CaptchaImageHandler> captchaImageHandlerList;
  private final MessageSourceAssertService assertService;

  @Override
  public CaptchaImageStreamResultDto createImage(CaptchaComponentConfig config) {
    return this.getHandlerAndCheck(config).createImage(config);
  }

  @Override
  public CaptchaImageBase64DataResultDto createBase64Data(CaptchaComponentConfig config) {
    return this.getHandlerAndCheck(config).createBase64Data(config);
  }

  private Optional<CaptchaImageHandler> getHandler(CaptchaComponentConfig config) {
    return this.captchaImageHandlerList.stream().filter(p -> p.support(config)).findFirst();
  }

  private CaptchaImageHandler getHandlerAndCheck(CaptchaComponentConfig config) {
    CaptchaImageHandler handler = this.getHandler(config).orElse(null);
    this.assertService.isNull(
        handler,
        "captcha.captcha-image-handler.is-null",
        new Object[] {Objects.isNull(config) ? "" : config.getId()},
        "[{0}]captchaComponentConfigId,没有对应实现");
    return handler;
  }
}
